package com.hs.srm.admin.modules.harmfulsubstance.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hs.srm.admin.modules.harmfulsubstance.dao.ReportRepositoryDao;
import com.hs.srm.admin.modules.harmfulsubstance.entity.ReportRepositoryEntity;
import com.hs.srm.admin.modules.harmfulsubstance.service.ReportRepositoryService;
import com.hs.srm.admin.modules.vendor.dao.VendorDao;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.vo.VendorCertificateVO;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.common.utils.QueryParam;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报告库表服务实现类
 *
 * @author ych
 * @since 2020-03-17 16:42:42
 */
@Service("reportRepositoryService")
public class ReportRepositoryServiceImpl extends ServiceImpl<ReportRepositoryDao, ReportRepositoryEntity> implements ReportRepositoryService {

    @Autowired
    private ReportRepositoryDao reportRepositoryDao;

    @Autowired
    private VendorDao vendorDao;

    /**
     * 列表数据查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        //测试报告编码
        String reportCode = (String) params.get("reportCode");

        //提交日期起
        String startDate = (String) params.get("startDate");

        //提交日期止
        String endDate = (String) params.get("endDate");

        //第三方报告委托单位
        String consignee = (String) params.get("consignee");

        //检测机构
        String testingInstitution = (String) params.get("testingInstitution");

        //是否有效，生效状态：0，有效；-2，无效；-1，作废；2，预警中
        String valid = (String) params.get("valid");

        //供应商编码
        String vendorCode = (String) params.get("username");

        //检测机构
        String vendorName = (String) params.get("vendorName");

        Page page = this.selectPage(new QueryParam<ReportRepositoryEntity>(params).getPage(),
                new EntityWrapper<ReportRepositoryEntity>()
                        .eq(StringUtils.isNotBlank(reportCode), "report_Code", reportCode)
                        .like(StringUtils.isNotBlank(consignee), "consignee", consignee)
                        .like(StringUtils.isNotBlank(testingInstitution), "testing_Institution", testingInstitution)
                        .eq(StringUtils.isNotBlank(valid), "valid", valid)
                        .ge(StringUtils.isNotBlank(startDate), "submit_date", startDate)
                        .le(StringUtils.isNotBlank(endDate), "submit_date", endDate)
                        .eq(StringUtils.isNotBlank(vendorCode), "vendor_code", vendorCode)
                        .like(StringUtils.isNotBlank(vendorName), "vendor_name", vendorName)
                        .orderDesc(Arrays.asList("valid", "expire_date"))
        );

        return new PageUtils(page);
    }

    /**
     * 通过测试报告编号查询数据
     *
     * @param codes
     * @return
     */
    @Override
    public List<ReportRepositoryEntity> selectBatchCodes(String[] codes, String vendorCode) {
        return reportRepositoryDao.selectBatchCodes(codes, vendorCode);
    }

    /**
     * 保存供应商新增的报告
     *
     * @param entity
     * @param request
     * @param vendorCode
     * @param vendorName
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveReport(ReportRepositoryEntity entity, HttpServletRequest request, String vendorCode, String vendorName) throws IOException, ServletException {
        Part part = request.getPart("attachFile");
        //文件保存路径
        String fileDir = SysConfig.getUploadPath() + "/harmfulsubstance/";
        //添加时间后缀
        String StrDate = new SimpleDateFormat("_yyyyMMddHHmmss").format(new Date());
        String fileName = part.getSubmittedFileName();
        String newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + StrDate + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
        //保存文件
        FileUtils.fileUpload(fileDir, newFileName, part);

        //上传文件路径
        entity.setAttach("/harmfulsubstance/" + newFileName);
        //创建时间
        entity.setCreateDate(new Date());
        //提交时间
        entity.setSubmitDate(new Date());
        //创建人
        entity.setCreator(vendorCode);
        //供应商编码、名称
        entity.setVendorCode(vendorCode);
        entity.setVendorName(vendorName);

        //更新报告,将更新前的报告设置失效
        if (StringUtils.isNotBlank(entity.getPkId())) {
            ReportRepositoryEntity preUpdate = reportRepositoryDao.selectById(entity.getPkId());
            //报告处于有效或预警中状态则将报告改为无效
            if (preUpdate.getValid() == ReportRepositoryEntity.YX || preUpdate.getValid() == ReportRepositoryEntity.YJZ) {
                preUpdate.setValid(ReportRepositoryEntity.WX);
            }
            reportRepositoryDao.updateById(preUpdate);
            //将更新前的数据保存到新的报告中
            entity.setOriginalReportCode(preUpdate.getReportCode());
            entity.setReplaced(1);
            entity.setSubmitter(preUpdate.getSubmitter());
            //将id清空
            entity.setPkId(null);
        } else {
            //新增报告，将替换的报告设置失效
            if (entity.getReplaced() == 1) {
                List<ReportRepositoryEntity> list = reportRepositoryDao.selectBatchCodes(entity.getOriginalReportCode().split(","), vendorCode);
                list.forEach(e -> {
                    e.setValid(ReportRepositoryEntity.WX);
                    reportRepositoryDao.updateById(e);
                });
            }
        }
        //保存供应商填写的报告
        reportRepositoryDao.insert(entity);
        return R.ok();
    }

    /**
     * 超过当前日期设置失效
     *
     * @param now 当前日期
     * @return
     */
    @Override
    public int setExpiredValid(String now) {
        return reportRepositoryDao.setExpiredValid(now);
    }

    /**
     * 到期前两周预警
     *
     * @param after 当前日期加两周
     * @return
     */
    @Override
    public int setWarningValid(String after) {
        return reportRepositoryDao.setWarningValid(after);
    }

    /**
     * 根据供应商编码获取即将过期的报告数量
     *
     * @param vendorCode
     * @return
     */
    @Override
    public Map<String, Integer> getWarningCount(String vendorCode) {
        Map<String, Integer> map = new HashMap<>();
        //即将过期
        map.put("nearly", 0);

        //获取供应商数据
        VendorInfoEntity vendor = new VendorInfoEntity();
        vendor.setSapCode(vendorCode);
        VendorInfoEntity entity = vendorDao.selectOne(vendor);
        //不能存在该供应商或用户不是供应商
        if (Objects.isNull(entity)) {
            return map;
        }

        Integer count = reportRepositoryDao.selectCount(new EntityWrapper<ReportRepositoryEntity>()
                .eq("vendor_code", vendorCode)
                .eq("valid", ReportRepositoryEntity.YJZ)
        );
        map.put("nearly", count);
        return map;
    }

    /**
     * 根据供应商编码，测试报告编号获取报告库中数据
     *
     * @param vendorCode
     * @param reportCode
     * @return
     */
    @Override
    public ReportRepositoryEntity reportDataByCode(String vendorCode, String reportCode) {
        return reportRepositoryDao.reportDataByCode(vendorCode, reportCode);
    }

    @Override
    public List<VendorCertificateVO> findFilePath(String vendorCode) {
        return this.reportRepositoryDao.findFilePath(vendorCode);
    }

}